﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class SitePages_frmSaleOrder : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        SaleManager sales = (SaleManager)Session[Constants.USER_SALE_MANAGER_CONN];
        if (sales == null)
        {
            sales = new SaleManager();
            Session.Add(Constants.USER_SALE_MANAGER_CONN, sales);
        }
        if (StoreComboBox.Items.Count == 0)
        {
            loadStoreRoomComboBox();
            loadItemComboBox();
            loadClientComboBox();
            loadCurrencyComboBox();
            loadTaxComboBox();
            postingDate.SelectedDate = DateTime.Now;
            deliveryDate.SelectedDate = DateTime.Now;
        }
        else
            loadInvoiceTable();
    }

    private void addDetail(ERPSIA.DocDetail detail, ERPSIA.Currency currency)
    {
        WebServiceAgent userAgent = (WebServiceAgent)Session[Constants.USER_WEB_SERVICE_CONN];
        ERPSIA.Item item = detail.Item;
        ERPSIA.StoreRoom store = detail.StoreRoom;
        ERPSIA.Tax tax = userAgent.GetDefaultTax();
        // Agregamos la información a la tabla
        TableRow row = new TableRow();
        TableCell itemCodeCell = new TableCell();
        itemCodeCell.Text = item.CodArticulo;
        TableCell descriptionCell = new TableCell();
        descriptionCell.Text = item.Descripción;
        TableCell quantityCell = new TableCell();
        quantityCell.Text = detail.Quantity.ToString("0.00") + " " + item.MeasureAcronim;
        TableCell unitPriceCell = new TableCell();
        unitPriceCell.Text = currency.Symbol + " " + detail.UnitCost.ToString("0.00");
        double subTotalAmount = Math.Round(detail.UnitCost * detail.Quantity, 2);
        double taxAmount = Math.Round(subTotalAmount * tax.Porcentaje);
        TableCell taxCell = new TableCell();
        taxCell.Text = currency.Symbol + " " + taxAmount.ToString("0.00");
        TableCell totalSoldCell = new TableCell();
        totalSoldCell.Text = currency.Symbol + " " + (subTotalAmount + taxAmount).ToString("0.00");
        TableCell storeCell = new TableCell();
        storeCell.Text = store.Code + " - " + store.Name;
        TableCell deleteCell = new TableCell();
        int index = InvoiceTable.Rows.Count - 1;
        DeleteButton btn = new DeleteButton(index);
        btn.Click += btnDelete_Click;
        btn.Text = "Eliminar";
        deleteCell.Controls.Add(btn);

        row.Cells.Add(itemCodeCell);
        row.Cells.Add(descriptionCell);
        row.Cells.Add(quantityCell);
        row.Cells.Add(unitPriceCell);
        row.Cells.Add(taxCell);
        row.Cells.Add(totalSoldCell);
        row.Cells.Add(storeCell);
        row.Cells.Add(deleteCell);
        InvoiceTable.Rows.Add(row);
        foreach (TableCell cell in row.Cells)
            cell.HorizontalAlign = HorizontalAlign.Center;
    }

    private void loadInvoiceTable()
    {
        SaleManager sales = (SaleManager)Session[Constants.USER_SALE_MANAGER_CONN];
        WebServiceAgent userAgent = (WebServiceAgent)Session[Constants.USER_WEB_SERVICE_CONN];
        ERPSIA.Currency currency = FinderManager.GetCurrency(Convert.ToInt32(CurrencyComboBox.SelectedValue), userAgent.GetCurrencies());
        TableRow header = InvoiceTable.Rows[0];
        InvoiceTable.Rows.Clear();
        InvoiceTable.Rows.Add(header);
        foreach (ERPSIA.DocDetail detail in sales.GetDetails())
            addDetail(detail, currency);
        taxLbl.Text = currency.Symbol + sales.TaxAmount.ToString();
        beforTaxLbl.Text = currency.Symbol + sales.SubTotalAmount.ToString();
        totalLbl.Text = currency.Symbol + (sales.SubTotalAmount + sales.TaxAmount).ToString();
    }

    /// <summary>
    /// Carga el combo box con las bodegas disponibles de la empresa, donde se pueden consultar los artículos
    /// </summary>
    private void loadStoreRoomComboBox()
    {
        StoreComboBox.Items.Clear();
        WebServiceAgent userAgent = (WebServiceAgent)Session[Constants.USER_WEB_SERVICE_CONN];
        ERPSIA.StoreRoom[] storeRooms = userAgent.GetStoreRooms();
        foreach (ERPSIA.StoreRoom store in storeRooms)
            StoreComboBox.Items.Add(new ListItem(store.Code + " - " + store.Name, store.Id.ToString()));
    }

    /// <summary>
    /// Carga el combo box con los artículos que tiene disponible la empresa
    /// </summary>
    private void loadItemComboBox()
    {
        ItemComboBox.Items.Clear();
        WebServiceAgent userAgent = (WebServiceAgent)Session[Constants.USER_WEB_SERVICE_CONN];
        ERPSIA.Item[] items = userAgent.GetAvailableItems();
        foreach (ERPSIA.Item item in items)
            ItemComboBox.Items.Add(new ListItem(item.CodArticulo + " - " + item.Descripción, item.Id.ToString()));
    }

    /// <summary>
    /// Carga el combo box con los clientes que están registrados en la empresa
    /// </summary>
    private void loadClientComboBox()
    {
        ClientComboBox.Items.Clear();
        WebServiceAgent userAgent = (WebServiceAgent)Session[Constants.USER_WEB_SERVICE_CONN];
        ERPSIA.AuxiliarAccount[] clients = userAgent.GetClients();
        foreach (ERPSIA.AuxiliarAccount client in clients)
            ClientComboBox.Items.Add(new ListItem(client.OwnerName, client.AccountID.ToString()));
        ERPSIA.AuxiliarAccount selectedClient = FinderManager.GetClient(Convert.ToInt32(ClientComboBox.SelectedValue), clients);
        CodeLabel.Text = selectedClient.AccountCode;
        NameLabel.Text = selectedClient.OwnerName;
    }

    /// <summary>
    /// Carga el combo box con los clientes que están registrados en la empresa
    /// </summary>
    private void loadCurrencyComboBox()
    {
        CurrencyComboBox.Items.Clear();
        WebServiceAgent userAgent = (WebServiceAgent)Session[Constants.USER_WEB_SERVICE_CONN];
        ERPSIA.Currency[] currencies = userAgent.GetCurrencies();
        foreach (ERPSIA.Currency currency in currencies)
            CurrencyComboBox.Items.Add(new ListItem(currency.Name, currency.Id.ToString()));
    }

    /// <summary>
    /// Carga el combo box con los clientes que están registrados en la empresa
    /// </summary>
    private void loadTaxComboBox()
    {
        TaxComboBox.Items.Clear();
        WebServiceAgent userAgent = (WebServiceAgent)Session[Constants.USER_WEB_SERVICE_CONN];
        ERPSIA.Tax defaultTax = userAgent.GetDefaultTax();
        TaxComboBox.Items.Add(new ListItem(defaultTax.Nombre + " - " + defaultTax.Porcentaje + "%", defaultTax.Porcentaje.ToString("00")));
        TaxComboBox.Enabled = false;
    }

    protected void ClientComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        WebServiceAgent userAgent = (WebServiceAgent)Session[Constants.USER_WEB_SERVICE_CONN];
        ERPSIA.AuxiliarAccount selectedClient = FinderManager.GetClient(Convert.ToInt32(ClientComboBox.SelectedValue), userAgent.GetClients());
        CodeLabel.Text = selectedClient.Name;
        NameLabel.Text = selectedClient.OwnerName;
    }

    public bool validateInputInfo()
    {
        if (txtCant.Text.Trim().Length == 0 )
        {
            lblCant.Text = "Debe ingresar la cantidad de artículos a agregar.";
            return false;
        }
        if (txtUnitPrice.Text.Trim().Length == 0)
        {
            lblPrice.Text = "Debe ingresar el precio unitario de los artículos a agregar.";
            return false;
        }
        double number;
        if (!double.TryParse(txtCant.Text, out number))
        {
            lblCant.Text = "Solo pueden ir números en la cantidad.";
            return false;
        }
        if (!double.TryParse(txtUnitPrice.Text, out number))
        {
            lblPrice.Text = "Solo pueden ir números en el precio unitario.";
            return false;
        }
        return true;
    }

    protected void btnAgregarItem_Click(object sender, EventArgs e)
    {
        lblPrice.Text = "";
        lblCant.Text = "";
        if(validateInputInfo())
        {
            SaleManager sales = (SaleManager)Session[Constants.USER_SALE_MANAGER_CONN];
            double quantity = double.Parse(txtCant.Text);
            WebServiceAgent userAgent = (WebServiceAgent)Session[Constants.USER_WEB_SERVICE_CONN];
            ERPSIA.Item item = FinderManager.GetItem(Convert.ToInt32(ItemComboBox.SelectedValue), userAgent.GetAvailableItems());
            ERPSIA.StoreRoom store = FinderManager.GetStore(Convert.ToInt32(StoreComboBox.SelectedValue), userAgent.GetStoreRooms());
            double unitCost = double.Parse(txtUnitPrice.Text);
            ERPSIA.Tax tax = userAgent.GetDefaultTax();
            sales.AddDetail(item, store, quantity, unitCost, tax);
            loadInvoiceTable();
        }
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        DeleteButton btn = (DeleteButton)sender;
        SaleManager sales = (SaleManager)Session[Constants.USER_SALE_MANAGER_CONN];
        sales.RemoveDetail(btn._index);
        loadInvoiceTable();
    }

    protected void btnAgregarDoc_Click(object sender, EventArgs e)
    {
        lblItem.Text = "";
        if (InvoiceTable.Rows.Count > 0)
        {
            WebServiceAgent userAgent = (WebServiceAgent)Session[Constants.USER_WEB_SERVICE_CONN];
            SaleManager sales = (SaleManager)Session[Constants.USER_SALE_MANAGER_CONN];
            bool result = userAgent.SaveSaleOrder(Convert.ToInt32(ClientComboBox.SelectedValue), postingDate.SelectedDate, deliveryDate.SelectedDate,
                    Convert.ToInt32(CurrencyComboBox.SelectedValue), 0, 0, sales.GetDetails());
            if (result)
            {
                Session[Constants.USER_SALE_MANAGER_CONN] = new SaleManager();
                loadInvoiceTable();
            }
            else
                lblItem.Text = "Error de conexión al ERP. Por favor intente de nuevo";
        }
        else
        {
            lblItem.Text = "Debe ingresar al menos un artículo en la orden de compra";
        }
    }
}